﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Belyn.Common.Web
{
    public class HttpRequest
    {

        public static string GetHttpCode(string url)
        {
            return GetHttpCode(url, Encoding.Default);
        }

        public static string GetHttpCode(string url,Encoding encoding)
        {
            string htmlCodeStr = "";
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse webResponse = null;
            webRequest.Method = "GET";
            
            StreamReader sr = null;
            try
            {
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                sr = new StreamReader(webResponse.GetResponseStream(), encoding);
                htmlCodeStr = sr.ReadToEnd();

            }
            catch (Exception ex)
            {
                throw new Exception("获取" + url + "源码出错：" + ex.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }

                if (webRequest != null)
                {
                    webRequest = null;
                }
                
            }

            return htmlCodeStr;
        }


    }
}
